package com.easy.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easy.entity.Sysstate;
import com.easy.entity.User;
import com.easy.service.UserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value="/login.htm")
	public String login(String mobile,String password,Model model,HttpSession session){
		
		String psw = new Md5Hash(password, "jianzhi").toString();
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(mobile, psw);
		try {
			subject.login(token);
			User user = userService.getUserByMobile(mobile);
			if(user.getBanflag()==(byte)1){
				subject.logout();
				model.addAttribute("msg", "账号已被禁用！请联系管理员QQ:1050495932！");
				return "login";
			}
			model.addAttribute("user", user);
			session.setAttribute("userinfo", user);
			return "redirect:/user/index.htm";
		} catch (Exception e) {
			model.addAttribute("msg", "账号或密码错误！请联系管理员QQ:1050495932！");
			return "login";
		}
	}
	
	@RequestMapping(value="/index.htm")
	public String index(Model model,HttpSession session){
		User user = (User)session.getAttribute("userinfo");
		model.addAttribute("user", user);
		return "index";
	}
	
	@RequestMapping(value="/pwdpage.htm")
	public String pwdpage(Model model,HttpSession session){
		User user = (User)session.getAttribute("userinfo");
		model.addAttribute("user", user);
		return "changepwd";
	}
	
	@RequestMapping(value="/changepwd.htm")
	public String changepwd(String pwd,Model model,HttpSession session){
		User user = (User)session.getAttribute("userinfo");
		user.setPassword(new Md5Hash(pwd, "jianzhi").toString());
		userService.updateUser(user);
		model.addAttribute("msg", "密码更改成功！请重新登录！");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
}
